<template>
  <view class="category-list-page">
    <view class="page-header">
     <view class="header-left" @click="navigateBack">
        <view class="icon icon-left" style="font-size: 24px; color: #333;">‹</view>
      </view>
      <text class="page-title">{{ categoryName }}</text>
      <view class="header-right"></view>
    </view>
    
    <!-- 排序选项 -->
    <view class="sort-bar">
      <view 
        v-for="sort in sortOptions" 
        :key="sort.value"
        class="sort-item"
        :class="{ active: currentSort === sort.value }"
        @click="handleSortChange(sort.value)"
      >
        <text>{{ sort.label }}</text>
        <view 
          v-if="sort.showArrow" 
          class="icon icon-arrow" 
          style="font-size: 14px; color: #007aff;" 
        >{{ sortOrder === 'desc' ? '↓' : '↑' }}</view>
      </view>
    </view>
    
    <!-- 壁纸列表 -->
    <wallpaper-grid 
      :wallpaper-list="wallpapers" 
      :has-more="hasMore" 
      :load-status="loadStatus"
      @wallpaper-click="navigateToDetail"
      @load-more="loadMoreWallpapers"
      @favorite="handleFavorite"
    />
  </view>
</template>

<script setup>
import { ref } from 'vue';
import {onLoad} from "@dcloudio/uni-app"

import WallpaperGrid from '../../components/wallpaper-grid.vue';

// 状态管理
const categoryId = ref('');
const categoryName = ref('分类壁纸');
const wallpapers = ref([]);
const page = ref(1);
const size = ref(20);
const hasMore = ref(true);
const loadStatus = ref('more');
const currentSort = ref('latest');
const sortOrder = ref('desc');

// 排序选项
const sortOptions = [
  { label: '最新', value: 'latest', showArrow: true },
  { label: '热门', value: 'popular', showArrow: true },
  { label: '收藏', value: 'favorite', showArrow: true }
];


onLoad((options) => {
  categoryId.value = options?.category_id || '';
  categoryName.value = options?.category_name ? decodeURIComponent(options.category_name) : '分类壁纸';
  if (categoryId.value) {
    loadWallpapers();
  }
});

// 加载壁纸
const loadWallpapers = async () => {
  try {
    uni.showLoading({ title: '加载中' });
    
    // 尝试调用云函数
    try {
      const res = await uniCloud.callFunction({
        name: 'getList',
        data: {
          page: page.value,
          size: size.value,
          categoryId: categoryId.value,
          sortBy: getSortField(),
          sortOrder: sortOrder.value
        }
      });
      console.log('getList获取云函数',res);
      if (res && res.result && res.result.code === 0) {
        if (page.value === 1) {
          wallpapers.value = res.result.data.list;
        } else {
          wallpapers.value = [...wallpapers.value, ...res.result.data.list];
        }
        hasMore.value = res.result.hasMore || false;
        loadStatus.value = 'more';
      } else {
        console.log('云函数调用失败或无数据，');
      }
    } catch (cloudError) {
      console.log('获取壁纸失败，:', cloudError);
    }
  } catch (error) {
    console.error('加载壁纸失败:', error);
    loadStatus.value = 'error';
    uni.showToast({ title: '加载失败', icon: 'none' });
    // 即使出错也显示模拟数据，避免空白页面
  } finally {
    uni.hideLoading();
  }
};



// 获取排序字段
const getSortField = () => {
  switch (currentSort.value) {
    case 'latest':
      return 'create_date';
    case 'popular':
      return 'download_count';
    case 'favorite':
      return 'favorite_count';
    default:
      return 'create_date';
  }
};

// 加载更多
const loadMoreWallpapers = async () => {
  if (!hasMore.value || loadStatus.value === 'loading') return;
  
  loadStatus.value = 'loading';
  page.value++;
  await loadWallpapers();
};

// 切换排序
const handleSortChange = (sortValue) => {
  if (currentSort.value === sortValue) {
    // 切换排序顺序
    sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc';
  } else {
    currentSort.value = sortValue;
    sortOrder.value = 'desc';
  }
  
  // 重置并重新加载
  page.value = 1;
  wallpapers.value = [];
  hasMore.value = true;
  loadWallpapers();
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 导航到详情
const navigateToDetail = (wallpaperId) => {
  uni.navigateTo({ url: `/pages/detail/detail?id=${wallpaperId._id}` });
};

// 处理收藏
const handleFavorite = async (wallpaper) => {
  const userInfo = uni.getStorageSync('uni_id_token');
  if (!userInfo) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    return;
  }
  
  try {
    // 模拟调用收藏云函数
    const index = wallpapers.value.findIndex(item => item._id === wallpaper._id);
    if (index !== -1) {
      wallpapers.value[index].is_favorite = !wallpapers.value[index].is_favorite;
      wallpapers.value[index].favorite_count += wallpapers.value[index].is_favorite ? 1 : -1;
    }
    
    uni.showToast({ 
      title: wallpapers.value[index].is_favorite ? '收藏成功' : '取消收藏',
      icon: 'success'
    });
  } catch (error) {
    console.error('收藏操作失败:', error);
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};
</script>

<style lang="less" scoped>
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.category-list-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    padding: 10px 16px;
    position: sticky;
    top: 0;
    z-index: 100;
    margin-top: 50rpx;
    .header-left,
    .header-right {
      width: 40px;
    }
    
    .header-left {
      display: flex;
      align-items: center;
    }
    
    .page-title {
      font-size: 18px;
      font-weight: 500;
      color: #333;
      flex: 1;
      text-align: center;
    }
  }
  
  .sort-bar {
    display: flex;
    background-color: #fff;
    margin-bottom: 12px;
    padding: 0 16px;
    
    .sort-item {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 12px 8px;
      margin-right: 24px;
      color: #666;
      font-size: 14px;
      
      .active {
        color: #007aff;
        font-weight: 500;
      }
    }
  }
}
</style>